package com.fingard.dsp.bank.directbank.cmb02.util;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

public class SignUtil {
	public String key = "";

	public static void main(String[] args) {
		SignUtil sign = new SignUtil();
		// 3D08099300EDA17E
		String pKey = "01DF47B1FD88146C";
		String pPlaintText = "20110718000660100004                        RMB00000000000000000200                                                                                           20110726  购买彩票投注金额2元                                                                                                                                                                                                                                                                                                                                                                    ";
		System.out.println(sign.ansi99(pKey, pPlaintText));
	}

	public SignUtil() {

	}

	/*
	 * 招行 ansi x9.9 mac 签名
	 */
	public static String ansi99(String key, String MsgData) {
		return ansi99(key, MsgData.getBytes());
	}

	public static String ansi99(String key, byte[] MsgData) {
		// System.out.println("mackey="+key);
		// System.out.println("MsgData="+(new String(MsgData)));
		byte[] b_BufArr1 = new byte[8];
		byte[] b_BufArr2 = new byte[8];
		byte[] Data = MsgData;
		int iGroup = 0;
		if (Data.length % 8 == 0)
			iGroup = Data.length / 8;
		else
			iGroup = Data.length / 8 + 1;

		byte[] keyBytes = null;
		try {
			keyBytes = Hex.decodeHex(key.toCharArray());
		} catch (DecoderException e) {
			e.printStackTrace();
		}
		System.out.println("keyBytes.len:" + keyBytes.length);
		CDesCipher des = new CDesCipher(keyBytes);
		for (int i = 0; i < iGroup; i++) {
			b_BufArr2 = getBytes(Data, 8 * i, 8);
			b_BufArr1 = xor(b_BufArr1, b_BufArr2);
			des.encrypt(b_BufArr1, b_BufArr2);
			b_BufArr1 = b_BufArr2;
		}

		return new String(Hex.encodeHex(b_BufArr2)).toUpperCase();

	}

	public static byte[] getBytes(byte[] bs, int start, int num) {
		byte[] bf = new byte[num];
		for (int i = 0; start + i < bs.length && i < num; i++) {
			bf[i] = bs[start + i];
		}
		return bf;
	}

	/**
	 * 
	 * 两个等长的数组做异或
	 * 
	 * @param source1
	 * 
	 * @param source2
	 * 
	 * @return
	 */
	public static byte[] xor(byte[] source1, byte[] source2) {
		new String();
		int len = source1.length;
		byte[] dest = new byte[len];
		for (int i = 0; i < len; i++) {
			dest[i] = (byte) (bytesToInt(source1[i]) ^ bytesToInt(source2[i]));
		}
		return dest;
	}

	public static int bytesToInt(byte bytes) {
		return bytes & 0xFF;
	}
}
